package com.koron.css2.projectCenter.impl;

import com.koron.css2.ServerInterface;
import com.koron.css2.projectCenter.bean.PjUseMatrBean;
import com.koron.css2.projectCenter.dto.PjUseMatrDto;
import com.koron.css2.projectCenter.mapper.PjUseMatrMapper;
import com.koron.css2.serviceManage.bean.RequestBean;
import com.koron.css2.serviceManage.bean.UserInfoBean;
import com.koron.css2.serviceManage.utils.JsonUtils;
import com.koron.util.Constant;
import com.koron.util.Tools;
import org.apache.commons.lang3.StringUtils;
import org.koron.ebs.mybatis.SessionFactory;
import org.swan.bean.MessageBean;

/**
 * 用料及领料保存
 * @author 许海宜
 * 2020年3月31日
 */
public class PjUseMatrSave implements ServerInterface {

	@Override
	public MessageBean<?> exec(SessionFactory factory, UserInfoBean userInfo, RequestBean req) {
		try {
			//将入参转换为QueryBean
			PjUseMatrDto dto = JsonUtils.objectToPojo(req.getData(), PjUseMatrDto.class);
			//字段校验
			if(StringUtils.isBlank(dto.getPjId())){
				return MessageBean.create(Constant.MESSAGE_INT_FAIL, "单据不存在。", null);
			}
			if(dto.getType() == null || (dto.getType() != 1 && dto.getType() != 2)){
				return MessageBean.create(Constant.MESSAGE_INT_FAIL, "类型错误。", null);
			}
			if(dto.getList() == null){
				return MessageBean.create(Constant.MESSAGE_INT_FAIL, "列表不能为空。", null);
			}
			
			//获取Mapper实例
			PjUseMatrMapper mapper = factory.getMapper(PjUseMatrMapper.class);
			
			//删除
			mapper.del(dto.getPjId(), dto.getType());
			//插入
			for (PjUseMatrBean bean : dto.getList()) {
				//字段校验
				if(StringUtils.isBlank(bean.getMatrNo())) {
					factory.close(false);
					return MessageBean.create(Constant.MESSAGE_INT_FAIL, "材料编号不能为空。", null);
				}
				if(StringUtils.isBlank(bean.getMatrName())) {
					factory.close(false);
					return MessageBean.create(Constant.MESSAGE_INT_FAIL, "材料名称不能为空。", null);
				}
				bean.setId(Tools.getObjectId());
				bean.setPjId(dto.getPjId());
				bean.setMatrMoney(bean.getMatrPrice()*bean.getMatrNum());
				mapper.add(bean, dto.getType());
			}
			//输出结果
			return MessageBean.create(Constant.MESSAGE_INT_SUCCESS, "保存成功", null);
		} catch (Exception e) {
			factory.close(false);
			logger.error("用水咨询-多水表保存失败"+e.getMessage(), e);
			return MessageBean.create(Constant.MESSAGE_INT_FAIL, "保存失败", null);
		}
	}


}
